package 设计模式.观察者模式.improve;

import java.util.ArrayList;
import java.util.List;

/**
 * 1.包含最新的天气情况信息
 * 2.含有CurrentConditions对象
 * 3.当数据有更新时，就主动的调用CurrentConditions对象update方法(含display),这样他们接入方就看到最新的信息
 */
public class WeatherData implements Subject {
    //温度，气压，适度
    private float temperature;
    private float pressure;
    private float humidity;
    //观察者集合
    private final List<Observer> observers;

    public WeatherData() {
        this.observers = new ArrayList<>();
    }

    public float getTemperature() {
        return temperature;
    }

    public float getPressure() {
        return pressure;
    }

    public float getHumidity() {
        return humidity;
    }

    public void dataChange() {
        //调用介入方的update
        notifyObservers();
    }

    //当数据有更新时，就调用setData
    public void setData(float temperature, float pressure, float humidity) {
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        //将dataChange最新的信息推送给介入方 currentConditions
        dataChange();
    }

    @Override
    public void registerObserver(Observer obj) {
        this.observers.add(obj);
    }

    @Override
    public void removeObserver(Observer obj) {
        if (observers.contains(obj)) {
            this.observers.remove(obj);
        }
    }

    @Override
    public void notifyObservers() {
        observers.forEach(observer -> {
            observer.update(this.temperature, this.pressure, this.humidity);
        });
    }
}
